/*
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-29 18:14:18
 * @Description  : 章节相关
 */
import { defineStore } from 'pinia'
import {  getChapterByPage } from '@/api/chapter'
import type { ChapterRes } from '@/types/chapter'
import { arrayToTree } from '@/utils'

interface ChapterStore {
  fullChapterList: ChapterRes[] // 章节选择器的数组，默认是一个完整的，包含根部门(id为1的)
}

export default defineStore('chapter', {
  state(): ChapterStore {
    return {
      fullChapterList: []
    }
  },
  actions: {
    setFullChapterList(fullChapterList: ChapterRes[]) {
      this.fullChapterList = fullChapterList
    },
    async getFullChapterList() {
      const res = await getChapterByPage({
        page: 1,
        pageSize: 9999,
      })

      const data = res.data.items.map((item) => {
        return {
          ...item,
          label: item.pid==='-1'? item.Exam.name+'-'+item.name:item.name,
          key: item.id,
          value:item.id
        }
      })

      data.unshift({
        pid:'-2',
        id: '-1',
        name: '全部',
        label: '全部',
        key: '-1',
        ParentChapter:null,
        Exam:null,
        examId:'',
        value:'-1'
      })

      // 转换为树形结构
      this.setFullChapterList(data)
    }
  },
  getters: {
    treeFullChapterList: (state) => {
      return arrayToTree(state.fullChapterList, 'pid', '-2')
    }
  }
})
